<?php

namespace App\Listeners;

use App\Events\TeacherBonus;
use App\User;
use App\UserBalanceRecord;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class HandleTeacherBonus
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  TeacherBonus  $event
     * @return void
     */
    public function handle(TeacherBonus $event)
    {
        $order = $event->order;
        $course = $order->courseable;
        $userId = $course->user_id ? $course->user_id : $course->course->user_id;
        $user = User::find($userId);
        if ($user && $course && $user->bonus_ratio > 0) {
            $bonus = $course->price * $user->bonus_ratio;
            $user->balance = $user->balance + $bonus;
            $user->save();

            // 记录
            UserBalanceRecord::create([
                'user_id' => $user->id,
                'type' => 1,
                'type_desc' => 'COURSE',
                'status' => 1,
                'amount' => $bonus,
                'trade_no' => $order->order_sn,
                'comment' => "用户{$user->name}购买课程，获得课程销售提成"
            ]);
        }
    }
}
